package com.itheima.controller;

import com.itheima.Service.ShoppingCartService;
import com.itheima.pojo.Result;
import com.itheima.pojo.ShoppingCart;
import com.itheima.pojo.ShoppingCartQueryParam;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/cart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public Result add(@RequestBody ShoppingCart cartItem) {
        cartItem.setUserId(BaseContext.getCurrentId());
        log.info("添加商品到购物车：{}", cartItem);
        shoppingCartService.add(cartItem);
        return Result.success();
    }

    /**
     * 更新购物车商品数量
     */
    @PutMapping("/update")
    public Result update(@RequestBody ShoppingCart cartItem) {
        cartItem.setUserId(BaseContext.getCurrentId());
        log.info("更新购物车商品：{}", cartItem);
        shoppingCartService.update(cartItem);
        return Result.success();
    }

    /**
     * 删除购物车商品
     */
    @DeleteMapping("/{productId}")
    public Result delete(@PathVariable Integer productId) {
        Integer userId = BaseContext.getCurrentId();
        log.info("删除购物车商品，用户ID：{}，商品ID：{}", userId, productId);
        shoppingCartService.delete(userId, productId);
        return Result.success();
    }

    /**
     * 批量删除购物车商品
     */
    @PostMapping("/batch-delete")
    public Result batchDelete( @RequestBody List<Integer> productIds) {
        Integer userId = BaseContext.getCurrentId();
        log.info("批量删除购物车商品，用户ID：{}，商品ID列表：{}", userId, productIds);
        shoppingCartService.batchDelete(userId, productIds);
        return Result.success();
    }

    /**
     * 清空购物车
     */
    @DeleteMapping("/clear")
    public Result clear() {
        Integer userId = BaseContext.getCurrentId();
        log.info("清空购物车，用户ID：{}", userId);
        shoppingCartService.clear(userId);
        return Result.success();
    }

    /**
     * 获取用户购物车列表
     */
    @GetMapping
    public Result list(ShoppingCartQueryParam param) {
        param.setUserId(BaseContext.getCurrentId());
        log.info("获取用户购物车列表：{}", param);
        return Result.success(shoppingCartService.list(param));
    }
}